from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from models import User
from schemas import UserCreate, UserUpdate, UserSchema, ResponseModel, PaginatedResponse
from api.deps import get_current_active_user, get_current_superuser
from utils import get_password_hash

router = APIRouter()

@router.get("", response_model=ResponseModel[PaginatedResponse[UserSchema]])
def get_users(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    username: Optional[str] = Query(None, description="用户名搜索"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取用户列表"""
    query = db.query(User)
    
    if username:
        query = query.filter(User.username.contains(username))
    
    # 计算总数
    total = query.count()
    
    # 分页
    users = query.offset((page - 1) * page_size).limit(page_size).all()
    
    # 准备用户响应数据
    users = [prepare_user_response(user) for user in users]
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=users
        )
    )

def prepare_user_response(user: User) -> User:
    """准备用户响应数据，确保is_active与status同步"""
    # 动态添加is_active属性，值与status同步
    setattr(user, "is_active", user.status == "1")
    return user

@router.get("/{user_id}", response_model=ResponseModel[UserSchema])
def get_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取用户详情"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=404,
            detail="用户不存在"
        )
    
    return ResponseModel(data=prepare_user_response(user))

@router.post("", response_model=ResponseModel[UserSchema])
def create_user(
    user_in: UserCreate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """创建用户"""
    # 检查用户名是否已存在
    user = db.query(User).filter(User.username == user_in.username).first()
    if user:
        raise HTTPException(
            status_code=400,
            detail="用户名已存在"
        )
    
    # 检查邮箱是否已存在
    if user_in.email:
        user = db.query(User).filter(User.email == user_in.email).first()
        if user:
            raise HTTPException(
                status_code=400,
                detail="邮箱已被注册"
            )
    
    # 创建新用户
    hashed_password = get_password_hash(user_in.password)
    db_user = User(
        username=user_in.username,
        password=hashed_password,
        email=user_in.email,
        phone=user_in.phone,
        department_id=user_in.department_id,
        is_active=user_in.is_active
    )
    
    # 添加角色
    if user_in.role_ids:
        from models import Role
        roles = db.query(Role).filter(Role.id.in_(user_in.role_ids)).all()
        db_user.roles = roles
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    return ResponseModel(data=db_user)

@router.put("/{user_id}", response_model=ResponseModel[UserSchema])
def update_user(
    user_id: int,
    user_in: UserUpdate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """更新用户"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=404,
            detail="用户不存在"
        )
    
    # 检查用户名是否已存在（排除当前用户）
    if user_in.username and user_in.username != user.username:
        existing_user = db.query(User).filter(User.username == user_in.username).first()
        if existing_user:
            raise HTTPException(
                status_code=400,
                detail="用户名已存在"
            )
    
    # 检查邮箱是否已存在（排除当前用户）
    if user_in.email and user_in.email != user.email:
        existing_user = db.query(User).filter(User.email == user_in.email).first()
        if existing_user:
            raise HTTPException(
                status_code=400,
                detail="邮箱已被注册"
            )
    
    # 更新字段
    update_data = user_in.dict(exclude_unset=True)
    if "password" in update_data:
        update_data["password"] = get_password_hash(update_data["password"])
    
    # 处理角色
    if "role_ids" in update_data:
        role_ids = update_data.pop("role_ids")
        from models import Role
        roles = db.query(Role).filter(Role.id.in_(role_ids)).all()
        user.roles = roles
    
    for field, value in update_data.items():
        setattr(user, field, value)
    
    db.commit()
    db.refresh(user)
    
    return ResponseModel(data=prepare_user_response(user))

@router.delete("/{user_id}", response_model=ResponseModel[dict])
def delete_user(
    user_id: int,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """删除用户"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=404,
            detail="用户不存在"
        )
    
    # 不允许删除自己
    if user.id == current_user.id:
        raise HTTPException(
            status_code=400,
            detail="不能删除当前登录用户"
        )
    
    db.delete(user)
    db.commit()
    
    return ResponseModel(data={"message": "用户删除成功"})